# -*- coding: utf-8 -*-
from datetime import datetime
from django import forms

from google.appengine.ext.db import djangoforms
from google.appengine.ext import db

from base.models import Invoice, School
from base.util.decorators import render_to, login_required

import logging

class InvoiceForm(djangoforms.ModelForm):
    class Meta:
        model = Invoice
        exclude = (
                   'id',
                   'sent_email',
                   'status',
                   'start_date',
                   'end_date',
                   'uint_price',
                   'count_classes',
                   'total_price',
                   )

@login_required
@render_to('invoice/form.html')
def create(request):
    data = request.GET.copy()
    school_id = data.get('school', '').strip()
    if school_id:
        school = School.get_using_id(int(school_id))
        form = InvoiceForm(initial={'school': school.key()})
    else:
        form = InvoiceForm()
    msg = ''
    if request.method == 'POST':
        form = InvoiceForm(request.POST)
        if form.is_valid():
            invoice = form.save(commit=False)
            school = invoice.school
            logging.info(school)
            if not school:
                msg = 'There is no school'
                return {'msg': msg}
            year = invoice.year
            month = invoice.month
            start = datetime(year, month, 1)
            end = datetime(year, month+1, 1)
            query = db.GqlQuery("SELECT * FROM OneClass WHERE school=:school AND status='Done' AND date >= :start AND date < :end ORDER BY date", school=school.key(), start=start, end=end)
            oneclasses = query.fetch(100)
            if not oneclasses:
                msg = 'There is no class'
                return {'msg': msg}
            invoice.start_date = oneclasses[0].date
            invoice.end_date = oneclasses[-1].date
            invoice.count_classes = len(oneclasses)
            invoice.total_price = invoice.count_classes * invoice.uint_price
            invoice.put()
            return invoice.get_absolute_url
    return {
            'form': form,
            'msg': msg,
            }

@login_required
@render_to('invoice/detail.html')
def detail(request, invoice_id):
    invoice = Invoice.get_using_id(int(invoice_id))
#    query = db.GqlQuery("SELECT * FROM OneClass WHERE school=:school AND status='Done' AND date >= :start AND date <= :end ORDER BY date", school=invoice.school.key(), start=invoice.start_date, end=invoice.end_date)
    query = db.GqlQuery("SELECT * FROM OneClass WHERE school=:school AND date >= :start AND date <= :end ORDER BY date", school=invoice.school.key(), start=invoice.start_date, end=invoice.end_date)
    oneclasses = query.fetch(100)

    return {
        'invoice': invoice,
        'oneclasses': oneclasses,
        }

@login_required
@render_to('invoice/list.html')
def year_list(request, year):
    query = Invoice.gql('WHERE year=:year ORDER BY month ASC', year=int(year))
    invoices = query.fetch(100)
    return {'invoices': invoices}

@login_required
@render_to('invoice/list.html')
def month_list(request, year, month):
    query = Invoice.gql('WHERE year=:year AND month=:month ORDER BY month ASC', year=int(year), month=int(month))
    invoices = query.fetch(100)
    return {'invoices': invoices}

@login_required
@render_to('invoice/list_form.html')
def school_list(request, school_id, year):
    school = School.get_using_id(int(school_id))
    query = Invoice.gql('WHERE school=:school AND year=:year ORDER BY month ASC', school=school.key(), year=int(year))
    invoices = query.fetch(100)
    return {'invoices': invoices}